import { Modal, Form, Input, Button, message, Spin, Select, Space } from "antd";
import React, { forwardRef, useState, useImperativeHandle } from "react";
import api_project from "@/api/project/index";
import { PlusOutlined, MinusOutlined } from '@ant-design/icons';
import { getDict } from "@/utils/localStorage";

const { TextArea } = Input;
const App = forwardRef((props, ref) => {
    const [id, setId] = useState("");
    const { callback } = props;
    const [ifShowModel, setifShowModel] = useState(false);
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const [imgUrlArr, setImgUrlArr] = useState([''])

    const [classify, setClassify] = useState('')
    const [type, setType] = useState('')

    const initialValues = {
        name: "",
        time: "",
        owner: "",
        type: null,
        remark: "",
        projectUrl: "",
        codeUrl: "",
        tag: [],
        imgUrl: imgUrlArr
    };
    //将需要的方法暴露出ref
    useImperativeHandle(ref, () => ({
        open,
    }));
    //页面初始化
    const open = (_id, _type, _classify) => {

        console.log('_classify',_classify)
        setId(_id);
        setClassify(_classify)
        setType(_type)
        form.resetFields(); //数据初始化
        setImgUrlArr([''])
        setifShowModel(true); //打开弹框
        if (_type === "update" || _type === "preview") getModel(_id);
    };
    //确定
    const handleOk = async () => {
        let valid;
        await form.validateFields().catch(() => {
            valid = true;
        });
        if (valid) return;

        console.log('type', type)
        console.log('classify', classify)

        if (type === "add") add();
        if (type === "update") update();
    };
    //取消
    const handleCancel = () => {
        setifShowModel(false);
    };
    //添加
    const add = async () => {
        setLoading(true);
        try {
            let data = form.getFieldsValue(true)
            data = Object.assign(form.getFieldsValue(true), { classify });
            let res = await api_project.addProject(data);
            setLoading(false);
            message.success(res.msg);
            setifShowModel(false);
            callback();
        } catch (err) {
            setLoading(false);
        }
    };
    //获取model
    const getModel = async (_id) => {
        setLoading(true);
        const res = await api_project.getmodel({ _id });
        setLoading(false);
        setImgUrlArr(res.data.imgUrl)
        form.setFieldsValue({
            name: res.data.name,
            time: res.data.time,
            owner: res.data.owner,
            type: res.data.type,
            remark: res.data.remark,
            projectUrl: res.data.projectUrl,
            codeUrl: res.data.codeUrl,
            coverUrl: res.data.coverUrl,
            tag: res.data.tag,
            imgUrl: res.data.imgUrl
        });
    };
    //编辑
    const update = async () => {
        setLoading(true);
        try {
            let res = await api_project.updateProject(Object.assign({ _id: id }, form.getFieldsValue(true), { classify }));
            setLoading(false);
            message.success(res.msg);
            setifShowModel(false);
            callback();
            form.resetFields();
            setImgUrlArr([''])
        } catch (err) {
            setLoading(false);
        }
    };

    return (
        <>
            <Modal title={type === "add" ? "新增" : type === "update" ? "编辑" : "预览"} open={ifShowModel} onOk={handleOk} onCancel={handleCancel} maskClosable={false} confirmLoading={loading}>
                <Spin spinning={loading} delay={500}>
                    <Form form={form} name="basic" disabled={type === "preview"} labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} initialValues={initialValues} autoComplete="off">
                        <Form.Item label="项目名称" name="name" rules={[{ required: true, message: "Please input your name!" }]}>
                            <Input placeholder="Please input your name!" />
                        </Form.Item>
                        <Form.Item label="开发周期" name="time" >
                            <Input placeholder="Please input your time!" />
                        </Form.Item>
                        <Form.Item label="项目所属" name="owner" rules={[{ required: true, message: "Please input your owner!" }]}>
                            <Input placeholder="Please input your owner!" />
                        </Form.Item>
                        <Form.Item label="项目类型" name="type" rules={[{ required: true, message: "Please input your type!" }]}>
                            <Select placeholder="Select a type" options={getDict("project_type")} ></Select>
                        </Form.Item>
                        <Form.Item label="项目标签" name="tag" rules={[{ required: true, message: "Please input your tag!" }]}>
                            <Select placeholder="Select a tag" mode="multiple" options={getDict("code_type")} ></Select>
                        </Form.Item>
                        <Form.Item label="项目封面" name="coverUrl" >
                            <Input placeholder="Please input your coverUrl!" />
                        </Form.Item>
                        <Form.List name="imgUrl">
                            {(fields, { add, remove }) => (
                                <>
                                    {fields.map((field, index) => (
                                        <Form.Item
                                            {...field}
                                            label={"项目图片"}
                                            name={['imgUrl', index]}
                                            key={field.key}

                                        >
                                            <Space.Compact style={{ width: '100%' }}>
                                                <Input
                                                    value={form.getFieldValue(['imgUrl', index])}
                                                    onChange={(e) => {
                                                        const newImgUrl = form.getFieldValue('imgUrl');
                                                        newImgUrl[index] = e.target.value;
                                                        form.setFieldsValue({ imgUrl: newImgUrl });
                                                    }}
                                                />
                                                {fields.length > 0 ? <Button style={{ width: '40px' }} icon={<MinusOutlined />} onClick={() => { remove(index) }} /> : null}
                                                <Button style={{ width: '40px' }} icon={<PlusOutlined />} onClick={() => { add() }} />
                                            </Space.Compact>
                                        </Form.Item>
                                    ))}
                                </>
                            )}
                        </Form.List>
                        <Form.Item label="线上地址" name="projectUrl" >
                            <Input placeholder="Please input your projectUrl!" />
                        </Form.Item>
                        <Form.Item label="代码托管" name="codeUrl" >
                            <Input placeholder="Please input your codeUrl!" />
                        </Form.Item>
                        <Form.Item label="项目描述" name="remark" rules={[{ required: true, message: "Please inpu   t your remark!" }]}>
                            <TextArea rows={2} />
                        </Form.Item>
                    </Form>
                </Spin>
            </Modal>
        </>
    );
});

export default App;
